﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Application.Service.Stall.Dto;
using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using OfficeOpenXml;
using System.Data;
namespace Admin.NET.Application;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using ClosedXML.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Drawing.Charts;
using System.Composition;
using Microsoft.AspNetCore.StaticFiles;
using Furion.VirtualFileServer;
using Furion.ClayObject.Extensions;
using DocumentFormat.OpenXml.Bibliography;
using Magicodes.ExporterAndImporter.Core.Models;

/// <summary>
/// 车位表服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class StallService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Stall> _stallRep;
    private readonly SqlSugarRepository<OccupantAudit> _occupantAudit;
    public StallService(SqlSugarRepository<Stall> stallRep, SqlSugarRepository<OccupantAudit> occupantAudit)
    {
        _stallRep = stallRep;
        _occupantAudit = occupantAudit;
    }


    #region 车位管理
    /// <summary>
    /// 分页查询车位表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询车位表")]
    public async Task<SqlSugarPagedList<StallOutput>> Page(PageStallInput input)
    {
        input.SearchKey = input.SearchKey?.Trim();

        var query = _stallRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.CarNo.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.CarNo), u => u.CarNo.Contains(input.CarNo.Trim()))
            .WhereIF(input.Operation > 0, u => u.Operation == input.Operation)

            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<Community>((u, roomid) => u.RoomId == roomid.Id)
            .LeftJoin<OccupantAudit>((u, roomid, peopleid) => u.PeopleId == peopleid.Id)
            .WhereIF(!string.IsNullOrEmpty(input.OccupantPhone), (u, roomid, peopleid) => peopleid.OccupantPhone.Contains(input.OccupantPhone))
            .WhereIF(!string.IsNullOrEmpty(input.PeopleIdOccupantName), (u, roomid, peopleid) => peopleid.OccupantName.Contains(input.PeopleIdOccupantName))
             .WhereIF(input.CarType > 0, (u, roomid, peopleid) => u.CarType == input.CarType)
            .WhereIF(input.RoomId > 0, (u, roomid, peopleid) => u.RoomId == input.RoomId)
            .Select((u, roomid, peopleid) => new StallOutput
            {
                Id = u.Id,
                CarNo = u.CarNo,
                RoomId = u.RoomId,
                RoomIdCommunityName = roomid.CommunityName,
                PeopleId = u.PeopleId,
                PeopleIdOccupantName = peopleid.OccupantName,
                OccupantPhone = peopleid.OccupantPhone,
                PeopleIdOccupantTime = peopleid.OccupantTime,
                CarType = u.CarType,
                Operation = u.Operation,
                OperationState = (StatusEnum)u.OperationState,
                StopCarMoney = u.StopCarMoney,
                CarState = u.CarState,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                IsDelete = u.IsDelete,
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加车位表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加车位表")]
    public async Task<long> Add(AddStallInput input)
    {
        var entity = input.Adapt<Stall>();
        await _stallRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除车位表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除车位表")]
    public async Task Delete(DeleteStallInput input)
    {
        var entity = await _stallRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _stallRep.FakeDeleteAsync(entity);   //假删除
        //await _stallRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新车位表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新车位表")]
    public async Task Update(UpdateStallInput input)
    {
        var entity = input.Adapt<Stall>();
        await _stallRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取车位表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取车位表")]
    public async Task<StallByIdDTO> Detail([FromQuery] QueryByIdStallInput input)
    {
        var list = await _stallRep.AsQueryable()
            .Where(x => x.Id == input.Id)
            .LeftJoin<OccupantAudit>((x, peopleId) => x.PeopleId == peopleId.Id)
            .Select((x, peopleId) => new StallByIdDTO
            {
                Id = x.Id,
                CarNo = x.CarNo,
                RoomId = x.RoomId,
                PeopleId = peopleId.Id,
                CarType = x.CarType,
                Operation = x.Operation,
                OccupantName = peopleId.OccupantName,
                OperationState = x.OperationState,
                StopCarMoney = x.StopCarMoney,
                CarState = x.CarState,
                OccupantPhone = peopleId.OccupantPhone,
                OccupantTime = peopleId.OccupantTime,
                OccupantExpirationTime = peopleId.OccupantExpirationTime
            }).FirstAsync();

        return list;
    }

    /// <summary>
    /// 获取车位表列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取车位表列表")]
    public async Task<List<StallOutput>> List([FromQuery] PageStallInput input)
    {
        return await _stallRep.AsQueryable().Select<StallOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取房屋Id列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "CommunityRoomIdDropdown"), HttpGet]
    [DisplayName("获取房屋Id列表")]
    public async Task<dynamic> CommunityRoomIdDropdown()
    {
        return await _stallRep.Context.Queryable<Community>()
                .Select(u => new
                {
                    Label = u.CommunityName,
                    Value = u.Id
                }
                ).ToListAsync();
    }
    /// <summary>
    /// 获取人员管理Id列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "OccupantAuditPeopleIdDropdown"), HttpGet]
    [DisplayName("获取人员管理Id列表")]
    public async Task<dynamic> OccupantAuditPeopleIdDropdown()
    {
        return await _stallRep.Context.Queryable<OccupantAudit>()
                .Select(u => new
                {
                    Label = u.OccupantName,
                    Value = u.Id
                }
                ).ToListAsync();
    }



    /// <summary>
    /// 导出
    /// </summary>
    /// <returns></returns>
    public async Task Exportxxx()
    {
        var stall = _stallRep.AsQueryable()

            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<Community>((u, roomid) => u.RoomId == roomid.Id)
            .LeftJoin<OccupantAudit>((u, roomid, peopleid) => u.PeopleId == peopleid.Id)
            .Select((u, roomid, peopleid) => new StallOutput
            {
                Id = u.Id,
                CarNo = u.CarNo,
                RoomId = u.RoomId,
                RoomIdCommunityName = roomid.CommunityName,
                PeopleId = u.PeopleId,
                PeopleIdOccupantName = peopleid.OccupantName,
                OccupantPhone = peopleid.OccupantPhone,
                PeopleIdOccupantTime = peopleid.OccupantTime,
                CarType = u.CarType,
                Operation = u.Operation,
                OperationState = (StatusEnum)u.OperationState,
                StopCarMoney = u.StopCarMoney,
                CarState = u.CarState,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                IsDelete = u.IsDelete,
            }).ToList();
        for (var i = 0; i < stall.Count(); i++)
        {
            var stalleDto = new ExcelDTO()
            {
                CarNo = stall[i].CarNo,
                PeopleIdOccupantName = stall[i].PeopleIdOccupantName,
                Operation = stall[i].Operation.ToString(),
                CarType = stall[i].CarType.ToString(),
            };
        }
        var tempPath = AppContext.BaseDirectory + "temp\\车位表111.xlsx";
        IExporter exporter = new ExcelExporter();
        var result = await exporter.Export(tempPath, stall);
        Console.WriteLine(result);
        //File.WriteAllBytes(filePath, result);

        //IImporter importer = new ExcelImporter();

        //var fileName = DateTime.Now.ToString("yyyyMMdd") + Path.GetFileName(tempPath);
        ////生成导出末班
        //var res = await importer.GenerateTemplate<ExcelDTO>(App.WebHostEnvironment.WebRootPath + "\\" + fileName);
        //return new FileStreamResult(new FileStream(res.FileName, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName };
    }

    #endregion

    /// <summary>
    /// excel导入
    /// </summary>
    /// <returns></returns>
    //[ApiDescriptionSettings(Name = "ImportExcel"), HttpGet]
    //  [DisplayName("excel导入")]
    //public DataSet ImportExcel(string filePath)
    //{
    //    DataSet ds = null;

    //    try
    //    {
    //        //打开文件
    //        FileStream fileStream = new FileStream(filePath, FileMode.Open);

    //        //读取文件流
    //        ExcelPackage package = new ExcelPackage(fileStream);

    //        //获取 sheet 表
    //        ExcelWorksheets worksheets = package.Workbook.Worksheets;

    //        ExcelWorksheet worksheet = null;

    //        ds = new DataSet();
    //        DataTable dt = null;

    //        for (int i = 1; i <= worksheets.Count; i++)
    //        {
    //            dt = new DataTable();
    //            dt.TableName = "table" + i.ToString();

    //            worksheet = worksheets[i];

    //            //获取行数
    //            int rowCount = worksheet.Dimension.End.Row;

    //            //获取列数
    //            int colCount = worksheet.Dimension.End.Column;

    //            //起始行为 1 
    //            int rowIndex = worksheet.Dimension.Start.Row;

    //            //起始列为 1 
    //            int colIndex = worksheet.Dimension.Start.Column;

    //            DataColumn dc = null;

    //            for (int j = colIndex; j <= colCount; j++)
    //            {
    //                dc = new DataColumn(worksheet.Cells[rowIndex, j].Value.ToString());
    //                dt.Columns.Add(dc);
    //            }

    //            rowIndex++;

    //            for (int k = rowIndex; k <= rowCount; k++)
    //            {
    //                DataRow dr = dt.NewRow();

    //                for (int l = colIndex; l <= colCount; l++)
    //                {
    //                    if (worksheet.GetValue(k, l) == null)
    //                    {
    //                        continue;
    //                    }

    //                    dr[l - 1] = worksheet.GetValue(k, l).ToString();
    //                }

    //                dt.Rows.Add(dr);
    //            }

    //            ds.Tables.Add(dt);
    //        }

    //        package.Dispose();

    //        worksheet = null;
    //        worksheets = null;
    //        package = null;

    //        fileStream.Close();
    //        fileStream.Dispose();
    //    }
    //    catch (Exception ex)
    //    {
    //        throw;
    //    }

    //    return ds;
    //}


}

